package cqgans.app.sunao.com.cqgans.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;

import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgans.ui.view.X5WebView;
import cqgans.app.sunao.com.cqgans.widget.LoadingDialog;
import cqgans.app.sunao.com.cqgansnew.R;

/**
 * Created by sunao on 2017/6/15.
 */
@ContentView(R.layout.activity_web)
public class WebActivity extends BaseActivity implements View.OnClickListener {
    private X5WebView mWebview;
    private ProgressBar mPageLoadingProgressBar = null;
    private String mUrl = "";
    private String title = "";
    private LoadingDialog dialog;
    @ViewInject(R.id.back)
    private TextView back;
    @ViewInject(R.id.close)
    private TextView close;
    private String postValue = "";
    private String js =  "";

    private String productNo;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        org.xutils.x.view().inject(this);
        productNo = getIntent().getStringExtra("productNo");
        try {
            dialog = new LoadingDialog(this, "加载中...");//
            dialog.show();
            initLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        js = "var e =";

    }

//    public void getSign() {
//        JSONObject info = new JSONObject();
//
//        try {
//            if (AppConstant.TARGET_URL.contains(AppConstant.JSS_PRODUCT_SHOW_URL)) {
//                JSONObject holder = new JSONObject();
//                holder.put("name", AppConstant.account != null ? AppConstant.account.userName : "");
//                holder.put("address", AppConstant.account != null ? AppConstant.account.userAddress : "");
//                info.put("holder", holder);
//                title = "产品详情";
//            }
//            if (AppConstant.TARGET_URL.contains(AppConstant.JSS_ACCOUNT_URL)) {
//                title = "个人中心";
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        postValue = "mobile=" + AppConstant.user.getMobile() + "&captionShow=0" + "&info=" + info.toString();
//        LogUtil.i("postValue= " + postValue);
////        postValue = "mobile=" +"13000000020" + "&info=" + info.toString();
//
//        String signStr = "appid=" + AppConstant.JSS_APP_ID + "&redirect_uri="
//                + AppConstant.TARGET_URL + "&timestamp=" + (System.currentTimeMillis() - 200000) / 1000 + AppConstant.JSS_APP_KEY;
//
//        mUrl = AppConstant.JSS_URL
//                + "appid=" + AppConstant.JSS_APP_ID + "&redirect_uri="
//                + AppConstant.TARGET_URL + "&timestamp=" + (System.currentTimeMillis() - 200000) / 1000 + "&sign=" + MD5.md5(signStr);
//        LogUtil.i(mUrl);
//
//
//    }

    private void initLayout() {
        getSign();
        mWebview = (X5WebView) findViewById(R.id.m_webview);

        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                LogUtil.i("shouldOverrideUrlLoading>>>>"+s);
                return false;
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
//                dialog.show();
                super.onPageStarted(webView, s, bitmap);
                LogUtil.i("onPageStarted>>>>"+s);


            }

            @Override
            public void onPageFinished(WebView view, String url) {
                System.out.println(url);
                LogUtil.i("onPageFinished>>>>"+url);

                if (view.getUrl().contains("account/center/index")) {
                    title = "个人中心";
                    settitleString(title);
                    findViewById(R.id.bar_view).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.bar_view).setVisibility(View.GONE);

                }

                dialog.close();
                super.onPageFinished(view, url);


            }
        });
        mWebview.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
                LogUtil.i("onJsConfirm>>>>"+s+"==="+s1+"==="+jsResult);

                return super.onJsConfirm(webView, s, s1, jsResult);
            }

            @Override
            public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
                LogUtil.i("onJsConfirm>>>>"+s+"==="+s1+"==="+s2+"==="+jsPromptResult);

                return super.onJsPrompt(webView, s, s1, s2, jsPromptResult);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                if (webView.getUrl().contains("account/center/index")) {
                    title = "个人中心";
                } else {
                    title = s;

                }
                settitleString(title);


            }
        });
        this.findViewById(R.id.close).setOnClickListener(this);
        this.findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.bar_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
        WebSettings webSetting = mWebview.getSettings();
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setSupportZoom(false);
        webSetting.setDisplayZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        webSetting.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        webSetting.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        webSetting.setAllowUniversalAccessFromFileURLs(false);
        //开启JavaScript支持
        // 支持缩放
        mWebview.setVerticalScrollBarEnabled(false);
        mWebview.setVerticalScrollbarOverlay(false);
        mWebview.setHorizontalScrollBarEnabled(false);
        mWebview.setHorizontalScrollbarOverlay(false);
//         webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);

//         webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
//         webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();


        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    @Override
    protected void onResume() {

        super.onResume();
        setTitleBar(title, 2);


    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 日期格式字符串转换成时间戳
     *
     * @return
     */
    public static String Date2TimeStamp() {
        try {
            long time = System.currentTimeMillis();
            String nowTimeStamp = String.valueOf(time / 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(time));
            return time + " " + date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                LogUtil.i("url= " + mWebview.getUrl());
                if (mWebview.getUrl().contains("finance/pay/success")) {
                    finish();
                }
                if (mWebview.canGoBack()) {
                    mWebview.goBack();
                } else {
                    finish();
                }
                break;
            case R.id.close:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {//当返回按键被按下
            this.findViewById(R.id.back).callOnClick();

        }
        return false;
    }

    private void getSign() {
        JSONObject info = new JSONObject();
        try {
            if (AppConstant.TARGET_URL.contains(AppConstant.JSS_PRODUCT_SHOW_URL)) {
                JSONObject holder = new JSONObject();
                holder.put("name", AppConstant.account != null ? AppConstant.account.userName : "");
                holder.put("address", AppConstant.account != null ? AppConstant.account.userAddress : "");
                info.put("holder", holder);
                title = "产品详情";
            }
            if (AppConstant.TARGET_URL.contains(AppConstant.JSS_ACCOUNT_URL)) {
                title = "个人中心";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postValue = "mobile=" + AppConstant.user.getMobile() + "&captionShow=0" + "&info=" + info.toString();

        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.QUERY_WEB_URL);
        JSONObject mjson = new JSONObject();
        try {
            if(AppConstant.TARGET_URL.contains(AppConstant.JSS_PRODUCT_SHOW_URL)) {
                mjson.put("type", "2");
                mjson.put("productNo", productNo);
            } else {
                mjson.put("type", "1");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.setAsJsonContent(true);
        params.setBodyContent(mjson.toString());
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @SuppressWarnings("WrongConstant")
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                System.out.println(result);
                try {
                    JSONObject resultJson = new JSONObject(result);
                    LogUtil.i(resultJson.toString());

                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {
                        Gson gson = new Gson();
                        if (resultJson.has("data") && resultJson.getJSONObject("data").has("url")) {
                            mUrl = resultJson.getJSONObject("data").getString("url");
//                            mWebview.pos(mUrl);
                            mWebview.postUrl(mUrl, EncodingUtils.getBytes(postValue, "BASE64"));
                        }
                    } else {
                        Toast.makeText(WebActivity.this, "获取地址失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(WebActivity.this, "获取地址失败", Toast.LENGTH_SHORT).show();
                finish();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                finish();
            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
}
